import React from 'react';
import PropTypes from 'prop-types';
import { Dialog, Form, Input, Field, Checkbox, Balloon } from '@teamix/ui';
import { ButtonIcon } from '@alife/devops-ui';
import intl from '../../../../../../../../../../locale';

const { Group: CheckboxGroup } = Checkbox;
const FormItem = Form.Item;

const TRIGGER = {
  PUSH_EVENTS: 'push_events',
  MERGE_REQUESTS_EVENTS: 'merge_requests_events',
  TAG_PUSH_EVENTS: 'tag_push_events',
  COMMENTS: 'note_events',
};

const formItemLayout = {
  labelCol: {
    span: 6,
  },

  wrapperCol: {
    span: 14,
  },
};

export default class ProjectModal extends React.Component {
  static propTypes = {
    trigger: PropTypes.element,
    closeModal: PropTypes.func,
    create: PropTypes.func,
  };

  static defaultProps = {
    trigger: null,
    closeModal: () => {},
  };

  constructor(props) {
    super(props);
    this.field = new Field(this);
    this.state = {
      submitting: false,
      isModalOpen: false,
    };
  }

  static getDerivedStateFromProps(props) {
    if (props.trigger) {
      return {};
    }
    return {
      isModalOpen: props.isModalOpen,
    };
  }

  URLValidator = (rule, value, callback) => {
    const { webhooks } = this.props;

    if (!value) {
      callback();
    }

    if (
      /(https?|ftp|file):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/.test(value) ===
      false
    ) {
      callback(
        intl.get({
          id: 'code-assets.containers.createWebhooks.TheUrlParameterIsInvalid',
          defaultMessage: 'URL 参数不合法',
        }),
      );
    }

    webhooks
      .filter((v) => v.type !== 'OrganizationHook')
      .forEach((item) => {
        if (item.url === value) {
          callback(
            intl.get({
              id: 'code-assets.containers.createWebhooks.TheSpecifiedUrlAlreadyExists',
              defaultMessage: 'URL 已存在',
            }),
          );
        }
      });

    callback();
  };

  showModal = () => {
    this.setState({
      isModalOpen: true,
    });
  };

  onClose = () => {
    this.setState({
      isModalOpen: false,
    });

    this.props.closeModal();
  };

  handleOk = () => {
    if (this.state.submitting) return;
    this.field.validate((errors) => {
      if (!errors) {
        this.setState({ submitting: true });
        const formData = this.field.getValues();
        formData.push_events = formData.events.includes(TRIGGER.PUSH_EVENTS);
        formData.merge_requests_events = formData.events.includes(TRIGGER.MERGE_REQUESTS_EVENTS);
        formData.tag_push_events = formData.events.includes(TRIGGER.TAG_PUSH_EVENTS);
        formData.note_events = formData.events.includes(TRIGGER.COMMENTS);
        this.props.create(formData, (isFail) => {
          if (!isFail) {
            this.field.reset();
          }
          this.setState({ submitting: false });
          this.onClose();
        });
      }
    });
  };

  onEventChane = (selectedItems) => {
    this.field.setValue('events', selectedItems);
  };

  messageValidator = (rule, value, callback) => {
    if (!value) {
      callback();
      return;
    }
    if (value.length > 200) {
      callback(
        intl.get({
          id: 'code-assets.containers.createWebhooks.TheDescriptionCannotExceedCharacters',
          defaultMessage: '描述长度不能超过200',
        }),
      );
    } else {
      callback();
    }
  };

  render() {
    const { init } = this.field;

    return (
      <React.Fragment>
        {this.state.isModalOpen ? (
          <Dialog
            title={
              <div>
                {intl.get({
                  id: 'code-assets.containers.createWebhooks.NewWebhook',
                  defaultMessage: '新建 Webhook',
                })}
              </div>
            }
            visible
            style={{ width: '600px', overflow: 'unset' }}
            onOk={this.handleOk}
            onCancel={this.onClose}
            onClose={this.onClose}
            footerActions={['cancel', 'ok']}
            okProps={{ loading: this.state.submitting }}
            className="create-webhook-dialog"
          >
            <Form {...formItemLayout} field={this.field} labelAlign="top">
              <FormItem label="URL" required>
                <Input
                  maxLength={1024}
                  hasLimitHint
                  autoFocus
                  placeholder="http://example.com"
                  {...init('url', {
                    rules: [
                      {
                        required: true,
                        message: intl.get({
                          id: 'code-assets.containers.createWebhooks.ThisParameterIsRequired',
                          defaultMessage: '该项为必填项',
                        }),
                      },

                      {
                        validator: this.URLValidator,
                      },
                    ],
                  })}
                />
              </FormItem>
              <FormItem
                label={
                  <div>
                    Secret Token
                    <Balloon.Tooltip
                      popupContainer={t => t.parentNode}
                      trigger={
                        <ButtonIcon
                          name="question-line"
                          style={{ marginLeft: 4, display: 'inline-block' }}
                        />
                      }
                      popupStyle={{
                        width: 470,
                        maxWidth: 'none',
                      }}
                      align="t"
                    >
                      {intl.get({
                        id: 'code-assets.containers.createWebhooks.TheRequestIsSentIn',
                        defaultMessage:
                          '在请求的 X-Codeup-Token HTTP头中发送，用于接收方验证请求合法性',
                      })}
                    </Balloon.Tooltip>
                  </div>
                }
              >
                <Input
                  maxLength={100}
                  hasLimitHint
                  placeholder={intl.get({
                    id: 'code-assets.containers.createWebhooks.EnterAToken',
                    defaultMessage: '请输入 Token',
                  })}
                  {...init('secret_token')}
                />
              </FormItem>
              <FormItem
                label={intl.get({
                  id: 'code-assets.containers.createWebhooks.Trigger',
                  defaultMessage: '触发器',
                })}
                {...formItemLayout}
                required
              >
                <CheckboxGroup
                  onChange={this.onEventChane}
                  {...init('events', {
                    initValue: [TRIGGER.PUSH_EVENTS],
                    rules: [
                      {
                        required: true,
                        message: intl.get({
                          id: 'code-assets.containers.createWebhooks.ThisParameterIsRequired',
                          defaultMessage: '该项为必填项',
                        }),
                      },
                    ],
                  })}
                >
                  <Checkbox id={TRIGGER.PUSH_EVENTS} value={TRIGGER.PUSH_EVENTS}>
                    {intl.get({
                      id: 'code-assets.containers.createWebhooks.PushEvents',
                      defaultMessage: '推送事件',
                    })}
                  </Checkbox>
                  <Checkbox id={TRIGGER.TAG_PUSH_EVENTS} value={TRIGGER.TAG_PUSH_EVENTS}>
                    {intl.get({
                      id: 'code-assets.containers.createWebhooks.TagPushEvent',
                      defaultMessage: '标签推送事件',
                    })}
                  </Checkbox>
                  <Checkbox id={TRIGGER.COMMENTS} value={TRIGGER.COMMENTS}>
                    {intl.get({
                      id: 'code-assets.containers.createWebhooks.Comments',
                      defaultMessage: '评论',
                    })}
                  </Checkbox>
                  <Checkbox
                    id={TRIGGER.MERGE_REQUESTS_EVENTS}
                    value={TRIGGER.MERGE_REQUESTS_EVENTS}
                  >
                    {intl.get({
                      id: 'code-assets.containers.createWebhooks.MergeRequestEvents',
                      defaultMessage: '合并请求事件',
                    })}
                  </Checkbox>
                </CheckboxGroup>
              </FormItem>
              <FormItem
                label={intl.get({
                  id: 'code-assets.containers.createWebhooks.Description',
                  defaultMessage: '描述',
                })}
                {...formItemLayout}
              >
                <Input.TextArea
                  {...init('description', {
                    rules: [{ validator: this.messageValidator }],
                  })}
                  placeholder={intl.get({
                    id: 'code-assets.containers.createWebhooks.EnterADescription',
                    defaultMessage: '请输入描述',
                  })}
                />
              </FormItem>
            </Form>
          </Dialog>
        ) : null}
        {!!this.props.trigger &&
          React.cloneElement(this.props.trigger, { onClick: this.showModal })}
      </React.Fragment>
    );
  }
}
